package com.zhuqi.configuration;

import cn.hutool.core.util.StrUtil;
import com.zhuqi.project.ReadFileProcess;
import com.zhuqi.service.CalcInterfaceCount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @author : ZhuQi
 * @version : 时间:2022/8/9 10:52 版本:
 * 项目启动监听 用于初始化数据
 */
@Component
@Slf4j
public class StartingProcess implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private ConfigurableApplicationContext context;

    @Autowired
    private FilePathList filePathList;

    @Autowired
    private PropertiesConfiguration propertiesConfiguration;

    @Autowired
    private CalcInterfaceCount configuration;

    @Autowired
    private ReadFileProcess readFileProcess;

    /**
     * Handle an application event.
     * 启动校验
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (StrUtil.isBlank(propertiesConfiguration.getPath())) {
            log.warn("LogConfiguration:路径参数为空，关闭容器!");
            context.close();
            return;
        }
        log.info("LogConfiguration:当前加载的路径:{}", propertiesConfiguration.getPath());
        File file = new File(propertiesConfiguration.getPath());
        if (!file.exists()) {
            log.warn("LogConfiguration:路径文件夹不存在，关闭容器!");
            context.close();
            return;
        }
        // 加载所有文件
        filePathList.getPaths();

        // 装载 URI Map 和 关键字
        configuration.initMapAndKeyWords();

        // 测试不执行业务逻辑
        if (propertiesConfiguration.getApp() != null && "test".equals(propertiesConfiguration.getApp())) {
            return;
        }

        // 启动调用方法
        readFileProcess.method();

        // 关闭容器
        // new ShutDownHook(context).run();
        // context.close();
    }
}
